package com.yswy.common.exception;

import com.yswy.common.model.ResultModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice(basePackages = {"com.yswy.app.controller", "com.yswy.backstage.controller"})
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class clazz,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        body = null == body ? "" : body;
        if ( body instanceof String) {
            if (body.toString().equalsIgnoreCase("success") || body.toString().equals("ok") ) {
                log.info(body.toString());
                return body.toString();
            }
        }
        if (body instanceof ResultModel) {
            return body;
        }
        ResultModel success = ResultModel.ok(body);
        return success;
    }

}
